{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e5a1a921",
   "metadata": {},
   "source": [
    "记录人：廖洪恩  \n",
    "记录时间：2022年4月12日 \n",
    "记录内容：文字识别  \n",
    "参考文档：https://console.faceplusplus.com.cn/documents/4888391\n",
    "       https://ai.baidu.com/ai-doc/OCR/1k3h7y3db"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3da52ae1",
   "metadata": {},
   "source": [
    "# OCR（光学字符识别）  \n",
    "* 通用文字识别  \n",
    "1.通用场景文字识别   \n",
    "2.网络文字识别   \n",
    "3.手写文字识别   \n",
    "4.二维码识别（二维码转文本）  \n",
    "* 卡证文字识别   \n",
    "1.身份证  \n",
    "2.银行卡  \n",
    "* 财务票据文字识别  \n",
    "1.增值税发票   \n",
    "2.火车票   \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "8de7375a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.a01acb83ef1a43c5115470365e5dd024.315360000.1965093899.282335-25948966', 'expires_in': 2592000, 'session_key': '9mzdX7gZkDVKOZFXpxoxAo1wBcbIBSzI6pGrjTEX99hqZegzFfOMPxfX87Dloa154dF7tSDsy2LWhdLRLMC0zITyg3lpIQ==', 'access_token': '24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': 'd46f985c184aa477520332b20fc007f3'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token'\n",
    "payload ={\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'YH7PdFatIi3l1cvAPONwoz3Z',\n",
    "    'client_secret':'lG6GOm60kLKxyKvnQS275W5qaqpvBFQR'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c8337f5e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wzsb_AI=response.json()['access_token']\n",
    "wzsb_AI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98623202",
   "metadata": {},
   "source": [
    "## 通用文字识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c7860a13",
   "metadata": {},
   "source": [
    "### 通用场景文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d15f8d41",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '每天看似周而复始'}, {'words': '真实都是新的开始'}, {'words': '再雷同的今天也不会是昨天的叠影'}], 'words_result_num': 3, 'log_id': 1513720518836571205}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('wz.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a941724c",
   "metadata": {},
   "source": [
    "### 网络文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "799c70bb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': 'A presentation of '}, {'words': 'Forrest Gump '}, {'words': '\" Life\\'slike a box of chocolates ,you never know '}, {'words': \"what you're gonna get \"}, {'words': 'S .Houel '}], 'words_result_num': 5, 'log_id': 1513723236498723316}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "网络图片文字识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('wlwz.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4258ade9",
   "metadata": {},
   "source": [
    "### 手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9ec1e388",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 59, 'left': 100, 'width': 265, 'height': 111}, 'words': '人生最好旅行'}, {'location': {'top': 66, 'left': 107, 'width': 399, 'height': 160}, 'words': '就基你在一个陌生的地方'}, {'location': {'top': 97, 'left': 138, 'width': 393, 'height': 177}, 'words': '发现一种久违:感动'}], 'words_result_num': 3, 'log_id': 1513723498022034404}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "手写文字识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \" https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('sxwz.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    \"top_num\":5\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17baf2bc",
   "metadata": {},
   "source": [
    "### 二维码识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "92494cf2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [{'text': ['API计算机视觉二维码识别!', 'Welcome to API!'], 'type': 'QR_CODE'}], 'codes_result_num': 1, 'log_id': 1513725497919125398}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "二维码识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('ewm.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img}\n",
    "access_token = '24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f746eae2",
   "metadata": {},
   "source": [
    "## 卡片识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b7d80fb3",
   "metadata": {},
   "source": [
    "### 身份证识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "f6431f7c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': {'姓名': {'location': {'top': 152, 'left': 376, 'width': 136, 'height': 51}, 'words': '廖洪恩'}, '民族': {'location': {'top': 242, 'left': 576, 'width': 32, 'height': 39}, 'words': '汉'}, '住址': {'location': {'top': 391, 'left': 355, 'width': 424, 'height': 103}, 'words': '广东省信宜市池洞镇蒲垌石堆村1号'}, '公民身份号码': {'location': {'top': 594, 'left': 511, 'width': 549, 'height': 57}, 'words': '44098320011214354X'}, '出生': {'location': {'top': 312, 'left': 368, 'width': 323, 'height': 44}, 'words': '20011214'}, '性别': {'location': {'top': 238, 'left': 373, 'width': 37, 'height': 39}, 'words': '女'}}, 'words_result_num': 6, 'idcard_number_type': 1, 'image_status': 'normal', 'log_id': 1513727036280276371}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "身份证识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/idcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('sfz.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img,\n",
    "    'id_card_side':'front'\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "247b9018",
   "metadata": {},
   "source": [
    "### 银行卡识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "f0da6b1f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': {'valid_date': '09/22', 'bank_card_number': '6217 0038 6000 2354 304', 'bank_name': '建设银行', 'bank_card_type': 1, 'holder_name': ''}, 'direction': 0, 'log_id': 1513727862291215766}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "银行卡识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/bankcard\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('yhk.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img\n",
    "\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "058be2cb",
   "metadata": {},
   "source": [
    "## 财务票据文字识别"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "77b30339",
   "metadata": {},
   "source": [
    "### 增值税发票"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "695c3cd9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 43, 'words_result': {'AmountInWords': '伍佰元整', 'InvoiceNumConfirm': '联居一贵', 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '8.849558'}], 'NoteDrawer': '无', 'SellerAddress': '无', 'CommodityNum': [{'row': '1', 'word': '50'}], 'SellerRegisterNum': '', 'MachineCode': '', 'Remarks': '途见第一行餐注徐国笔二行路件琼阳笔一行警件', 'SellerBank': '无', 'CommodityTaxRate': [{'row': '1', 'word': '13%'}], 'TotalTax': '57.52', 'InvoiceCodeConfirm': '3100203130', 'CheckCode': '11', 'InvoiceCode': '3100203130', 'InvoiceDate': '3', 'PurchaserRegisterNum': '91ZXCVB123456789FF', 'InvoiceTypeOrg': '上海增值税专用发票', 'OnlinePay': '', 'Password': '无1无710', 'Agent': '否', 'AmountInFiguers': '500.00', 'PurchaserBank': '火星发展银行9996661236', 'Checker': '张三', 'City': '', 'TotalAmount': '442.48', 'CommodityAmount': [{'row': '1', 'word': '442.48'}], 'PurchaserName': '月球移民计划发展有限公司', 'CommodityType': [{'row': '1', 'word': '校105'}], 'Province': '上海', 'InvoiceType': '专用发票', 'SheetNum': '第一联：记账联', 'PurchaserAddress': '可点市上方90交类左侧按铝全屏审核、无灵后请一点市下螺.他可在发票生成火星移民经济开发园区888号019-55558888', 'CommodityTax': [{'row': '1', 'word': '157.52'}], 'CommodityPlateNum': [], 'CommodityUnit': [{'row': '1', 'word': '件'}], 'Payee': '李四', 'CommodityName': [{'row': '1', 'word': '*服装*男上衣'}], 'SellerName': '', 'InvoiceNum': '4844'}, 'log_id': 1513728731737428877}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "增值税发票识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url =  \"https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('zss.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img\n",
    "\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5d5555b",
   "metadata": {},
   "source": [
    "### 火车票"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "b9356fd5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 13, 'words_result': {'id_num': '1301231997****0015', 'serial_number': '65870300070929X006460', 'ticket_num': 'X006460', 'seat_num': '01车047号', 'time': '13:50', 'date': '2019年09月29日', 'name': '高海港', 'destination_station': '石家庄站', 'seat_category': '新空调硬座', 'starting_station': '广州站', 'sales_station': '汕尾', 'train_num': 'Z90', 'ticket_rates': '￥224.0元'}, 'direction': 0, 'log_id': 1513729370107044892}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "火车票识别（高精度版）\n",
    "'''\n",
    "\n",
    "request_url =  \"https://aip.baidubce.com/rest/2.0/ocr/v1/train_ticket\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('hcp.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "access_token ='24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966'\n",
    "payload={\n",
    "    'access_token':'24.db22ddbe968e6964325b0ddfc0600f0c.2592000.1652325899.282335-25948966',\n",
    "    'image':img\n",
    "\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a8d96a07",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
